package com.baoteng.rbspy.jobs;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.baoteng.rbspy.cache.LocalCacheManager;
import com.baoteng.rbspy.config.car.RbSysConfig;
import com.baoteng.rbspy.model.Model;
import com.baoteng.rbspy.model.proposal.InfoProposal;
import com.baoteng.rbspy.model.request.proposal.QueryProposalRequest;
import com.baoteng.rbspy.model.request.proposal.QueryUnderWriteFlag;
import com.baoteng.rbspy.mq.MessageHandler;
import com.baoteng.rbspy.service.ProposalService;
import com.google.common.collect.Lists;

@Component
public class ProposalHolder {
	
	private static final Logger logger = LoggerFactory.getLogger(ProposalHolder.class);
	
	@Autowired
	RbSysConfig rbSysConfig;
	
	@Autowired
	LocalCacheManager statusCache;
	
	final List<Integer> seqNo = Lists.newArrayList(1,2,3,4,5,6,7,8,9,10);
	
	final static int PAGE_LIMIT = 20;
	@Autowired
	ProposalService proposalService;
	
	@Autowired
	MessageHandler messageHandler;
	
//	@Scheduled(fixedDelay = 2 * 60 * 1000)
//	public void submitJob() {
//		logger.info("ProposalHolder submitJob start.");
//		ConcurrentMap<String,Integer> jobs = statusCache.getJobs();
//		jobs.entrySet().parallelStream().forEach(c->{
//			logger.info("ProposalHolder submitJob item:quoteNum-{},value-{}",c.getKey(),c.getValue());
//			statusCache.getQuote(c.getKey()).ifPresent(quote->{
//				ApplyQuoteResponse quoteResponse = (ApplyQuoteResponse) quote;
//				HeRequest request = new HeRequest();
//				request.setQuoteNum(c.getKey());
//				request.setBusNum(quoteResponse.getBiNo());
//				request.setForNum(quoteResponse.getCiNo());
//				try {
//					HeResponse response = proposalService.submitUndwrt(request);
//					if(response!=null && response.getBusinessStatus()!=null) {
//						logger.error("ProposalHolder submitJob done.quoteNum-{}",c.getKey());
//						WSPackage<HeResponse> _e = new WSPackage<HeResponse>();
//						_e.setEntity(PackageEntity.ORDER);
//						_e.setType(PackageType.NOTIFY);
//						_e.setData(response);
//						messageHandler.producer(_e);
//						if(c.getValue()>5) statusCache.removeJob(c.getKey());
//						else statusCache.putJob(c.getKey(), c.getValue()+1);
//					}
//				} catch (Exception e) {
//					logger.error("ProposalHolder submitJob error.",e);
//				}
//			});;
//		});
//		logger.info("ProposalHolder submitJob end.");
//	}
	
	@Scheduled(fixedDelay = 5 * 60 * 1000)
	public void statusRefresh() {
		final LocalDate _date = LocalDate.now();
		statusCache.getPproposalStatus();
		logger.info("ProposalHolder jobs start.");
		List<InfoProposal> result = Lists.newArrayList();
		seqNo.stream().filter(i ->{
			QueryProposalRequest request = new QueryProposalRequest();
			request.setComCode(rbSysConfig.getComCode());
			request.setOperatorCode(rbSysConfig.getOperatorCode());
			request.setOperateDate(_date.plusDays(-5).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
			request.setOperateDate2(_date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
			request.setUnderWriteFlag(Lists.newArrayList(new QueryUnderWriteFlag("3","2"),new QueryUnderWriteFlag("4","4")));
			request.setPageSize(50);
			request.setPageNo(i);
			Model<InfoProposal> response =null;
			try {
				response = proposalService.listProposal(request);
				if(response!=null && response.getData()!=null && response.getData().size()>0) {
					result.addAll(response.getData());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return response==null || response.getData()==null || response.getData().isEmpty()?true:false;
		}).findFirst().orElseGet(()->{
			if(seqNo.size()<PAGE_LIMIT) seqNo.add(seqNo.size()+1);
			return seqNo.size();
		});
		statusCache.refreshProposalStatus(result);
		logger.info("ProposalHolder jobs done.refresh count:{}",result.size());
	}
	
	@Scheduled(cron = "0 3 0 * * ?")
	public void cleanup() {
		final LocalDate _date = LocalDate.now();
		QueryProposalRequest request = new QueryProposalRequest();
		request.setComCode(rbSysConfig.getComCode());
		request.setOperatorCode(rbSysConfig.getOperatorCode());
		request.setOperateDate(_date.plusDays(-12).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
		request.setOperateDate2(_date.plusDays(-1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
		request.setStartDate(_date.plusDays(-12).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
		request.setStartDate2(_date.plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
		request.setUnderWriteFlag(Lists.newArrayList(new QueryUnderWriteFlag("1","0")));
		request.setPageSize(10);
		request.setPageNo(1);
		try {
			Model<InfoProposal> response = proposalService.listProposal(request);
			if(response!=null && response.getData()!=null && response.getData().size()>0) {
				StringBuilder sb = new StringBuilder();
				response.getData().stream().forEach(p->{
					sb.append(p.getProposalNo()).append(",");
				});
				logger.info("ProposalHolder cleanup jobs done.cleanup proposalNos:{} count:{},",sb.toString(),response.getData().size());
				proposalService.delProposal(sb.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
